﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UtilsBase;
using UtilsCache;
using UtilsORM;
using UtilsORM.MySqlData;

namespace GatewayServerService.Data
{
    public class DBIotDeviceValueCurrentCache
    {



        /// <summary>
        /// 缓存增加 获取变量列表
        /// </summary>
        /// <param name="cguid"></param>
        /// <returns></returns>
        public List<iot_device_value_current> getValueCurrentListByCache(string dguid)
        {

            List<iot_device_value_current> list = UtilMemoryCacheHelper.get<List<iot_device_value_current>>("iot_device_value_current_" + dguid);
            if (list == null || list.Count == 0)
            {
                EFYihongIotContext ef = new EFYihongIotContext();
                list = ef.iot_device_value_current.Where(c => c.vc_d_guid == dguid).ToList();
                UtilMemoryCacheHelper.set("iot_device_value_current_" + dguid, list, 1);
            }
            return list;
        }
        public iot_device_value_current getValueCurrentByCache(string dguid, string key)
        {

            iot_device_value_current model = UtilMemoryCacheHelper.get<iot_device_value_current>("iot_device_value_current_" + dguid + key);
            if (model == null)
            {
                EFYihongIotContext ef = new EFYihongIotContext();
                model = ef.iot_device_value_current.Where(c => c.vc_d_guid == dguid && c.vc_key == key).FirstOrDefault();
                UtilMemoryCacheHelper.set("iot_device_value_current_" + dguid + key, model, 1);
            }
            return model;
        }

        /// <summary>
        /// 读取ServiceCloudDeviceValueLog最新写入值的缓存，或读取表中的数据，如果有新值必定会在ServiceCloudDeviceValueLog中更新redis
        /// </summary>
        /// <param name="dguid"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public string getDeviceValue(string dguid, string key)
        {

            string dvalue = UtilMemoryCacheHelper.get<string>("deviceKey_" + dguid + key);
            if (dvalue == null)
            {
                EFYihongIotContext ef = new EFYihongIotContext();
                iot_device_value_current model = ef.iot_device_value_current.Where(c => c.vc_d_guid == dguid && c.vc_key == key).FirstOrDefault();
                if (model != null)
                {
                    //和ServiceCloudDeviceValueLog写入值和读取值，实时把设备值写入缓存，提高访问效率
                    UtilMemoryCacheHelper.set("deviceKey_" + dguid + key, model.vc_value, 60);
                    dvalue = model.vc_value;
                }
            }
            return dvalue;
        }
    }
}
